//
//  LoginManager.m
//  6p
//
//  Created by weienjie on 15/3/3.
//  Copyright (c) 2015年 fenfen. All rights reserved.
//

#import "LoginManager.h"
#import "WeiXinManager.h"
#import "SinaManager.h"
#import "QQManager.h"
#import "AppDelegate.h"
#import "NSString+MD5.h"
#import "AESTool.h"
#import "GongXiView.h"
#import "ShoppingCarVC.h"

//登录状态，类型
#define kLoginStatus            @"loginStatus"
#define kLoginType              @"loginType"

#define kAccount    @"account"
#define kPassword   @"password"

//加密混淆字符串
#define EncryptString @"gyt^$&^*vjfGJ$$&*MV"

#define ThirdLoginUrl @"/api/ApiUser/loginSocialite"

//注册统计
#define REG_TONGJI_URL @"register"

@implementation LoginManager

/*
 YES: 登录状态，启动时需要自动登录。
 NO: 非登录状态，启动时不需要自动登录。
 需要持久化保存。
 */
+ (BOOL)loginStatus
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:kLoginStatus];
}

+ (void)setLoginStatus:(BOOL)status
{
    [[NSUserDefaults standardUserDefaults] setBool:status forKey:kLoginStatus];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/*
 登录类型：手游秀账号登录，微信登录，新浪登录，QQ登录
 需要持久化保存。
 */
+ (LoginType)loginType
{
    return [[NSUserDefaults standardUserDefaults] integerForKey:kLoginType];
}

+ (void)setLoginType:(LoginType)type
{
    [[NSUserDefaults standardUserDefaults] setInteger:type forKey:kLoginType];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/*
 自动登录，loginStatus = YES时，根据loginType的值去自动登录
 */
+ (void)autoLogin
{
    if (self.loginStatus)
    {
        switch (self.loginType)
        {
            case LoginType_weixin:
                [WeiXinManager weixinAutoLogin];
                break;
            case LoginType_sina:
                [[SinaManager sharedInstance] sinaAutoLogin];
                break;
            case LoginType_qq:
                [[QQManager sharedInstance] qqAutoLogin];
                break;
            case LoginType_oola:
                [self oolaAutoLogin];
                break;
            default:
                break;
        }
    }
    else
    {
        //第一次启动安装app时统计
        [self uploadDeviceToken];//上传设备信息
    }
}

/*
 主动登出
 */
+ (void)loginOut
{

    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kPassword];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (self.loginStatus)
    {
        self.loginStatus = NO;
        [[NSUserDefaults standardUserDefaults] setBool:self.loginStatus forKey:kLoginStatus];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        switch (self.loginType) {
            case LoginType_oola:
                break;
            case LoginType_weixin:
                [WeiXinManager weixinLogout];
                break;
            case LoginType_sina:
                [[SinaManager sharedInstance]  sinaLogout];
                break;
            case LoginType_qq:
                [[QQManager sharedInstance] qqLogout];
                break;
            default:
                break;
        }
    }
}

/*
 账号自动登录（自动登录不需要再上传一边设备信息）
 */
+ (void)oolaAutoLogin
{
    NSString *account = [[NSUserDefaults standardUserDefaults] objectForKey:kAccount];
    NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:kPassword];
    if (account && password)
    {
    }
}
/*
 第三方登录
 */
+ (void)loginWithData:(id)data type:(LoginType)type
{
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [WYPublic addZheZhaoToWindowWithTitle:nil];
    NSMutableDictionary *params = nil;
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *channelId = [user objectForKey:@"TongJi_channelId"];
    NSString *unionId = [user objectForKey:@"TongJi_unionId"];
    NSString *uid = [user objectForKey:@"TongJi_uid"];
    NSString *privateKey_String = nil;
    NSString *ret_json = nil;
    NSData *jsondata = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
    if (jsondata) {
        ret_json = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];
    }
    
    if (uid != nil) {
        privateKey_String = [[NSString alloc] initWithFormat:@"%@%@",ret_json,uid];
    }
    else
    {
        if (!unionId) {
            unionId = @"2";
        }
        if (!channelId) {
            channelId =  @"2";
        }
        privateKey_String = [[NSString alloc] initWithFormat:@"%@%@%@",ret_json,unionId,channelId];
    }
    NSLog(@"%@",privateKey_String);
    privateKey_String = [NSString stringWithFormat:@"%@%@%@",EncryptString,privateKey_String,EncryptString];
    NSLog(@"%@",privateKey_String);
    NSString *privateKeyString_MD5 = [privateKey_String MD5Hash];
    NSLog(@"%@",privateKeyString_MD5);
    NSString *privateKey = [privateKeyString_MD5 substringWithRange:NSMakeRange(4, 16)];
    NSLog(@"%@",privateKey);
    
    NSString *ret_json_Encrypt = [AESTool encryptData:@"ret_json" withKey:privateKey];
    NSString *ret_jsonValue_encrypt = nil;
    if (ret_json != nil) {
        ret_jsonValue_encrypt = [AESTool encryptData:ret_json withKey:privateKey];
    }
    
    NSString *op_union_id_Encrypt = [AESTool encryptData:@"op_union_id" withKey:privateKey];
    NSString *op_union_idValue_Encrypt = nil;
    if (unionId!=nil) {
        op_union_idValue_Encrypt = [AESTool encryptData:unionId withKey:privateKey];
    }
    
    NSString *op_channel_id_Encrypt = [AESTool encryptData:@"op_channel_id" withKey:privateKey];
    NSString *op_channel_idValue_Encrypt = nil;
    if (channelId != nil) {
        op_channel_idValue_Encrypt = [AESTool encryptData:channelId withKey:privateKey];
    }
    
    NSString *op_parent_uid_Encrypt = [AESTool encryptData:@"op_parent_uid" withKey:privateKey];
    NSString *op_parent_uidValue_Encrypt = nil;
    if (uid != nil) {
        op_parent_uidValue_Encrypt = [AESTool encryptData:uid withKey:privateKey];
    }
    params = [[NSMutableDictionary alloc] init];
    [params setValue:privateKey forKey:@"private_key"];
    [params setValue:ret_jsonValue_encrypt forKey:ret_json_Encrypt];
    if (op_union_idValue_Encrypt) {
        [params setValue:op_union_idValue_Encrypt forKey:op_union_id_Encrypt];
    }
    if (op_channel_idValue_Encrypt) {
        [params setValue:op_channel_idValue_Encrypt forKey:op_channel_id_Encrypt];
    }
    if (op_parent_uidValue_Encrypt) {
        [params setValue:op_parent_uidValue_Encrypt forKey:op_parent_uid_Encrypt];
    }
    
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,ThirdLoginUrl] Parameters:params successBlock:^(NSDictionary *dic) {
        NSNumber *ret = dic[@"ret"];
        if (ret.intValue == 0) {
            
            //保存用户信息
            NSDictionary *userinfo = dic[@"data"];
            if ([[userinfo objectForKey:@"is_register"] integerValue] == 1) {
                //统计接口
                [self tongji];
            }
            [UserInfo writeUserInfoWithDic:userinfo];
            //退出登录界面
            //通知刷新购物车
            [WYPublic logOrRegistSuccess];
            [ShoppingCarVC shareShoppingCarVC].firstFlag = YES;
            
            ShoppingCarVC *vc = [ShoppingCarVC shareShoppingCarVC];
            vc.firstFlag = YES;
            
            NSInteger index = 2;
            NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
            if (show_shopping.integerValue == 1) {
                //显示
                index = 3;
            }
            [[WYMainTabBarVC shareMainTaBarVC] changeSelectedWithIndex:index];
            
            //恭喜
//            NSString *money = [WYPublic getUsefullStr:dic[@"data"][@"money"]];
//            if ([money isEqualToString:@"1"]) {
//                GongXiView *gongxi = [[GongXiView alloc]init];
//                [WINDOW addSubview:gongxi];
//            }
            
        }else{
            [WYPublic showMessageWithTitle:nil Msg:dic[@"msg"]];
        }
        [WYPublic removeZheZhaoToWindow];
    } failedBlock:^{
        [WYPublic removeZheZhaoToWindow];
    } needLog:NO];

    
}


+ (void)tongji
{
    NSDictionary *params = @{};
    [WYRequest startPostForTongJiWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_YX_IP,REG_TONGJI_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        
    } failedBlock:^{
        
    } needLog:NO];
}

/*
 账号登录
 */
+ (void)oolaLoginWithAccount:(NSString *)account password:(NSString *)psw
{
    

}






@end
